package com.dream.keigezhushou.Activity.acty.login;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.dream.keigezhushou.Activity.Uiutils.JsonParse;
import com.dream.keigezhushou.Activity.Uiutils.ToastUtils;
import com.dream.keigezhushou.Activity.activity.BaseActivity;
import com.dream.keigezhushou.Activity.url.NetURL;
import com.dream.keigezhushou.R;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FindPassActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_return)
    ImageView ivReturn;
    @BindView(R.id.iv_delete_pass)
    ImageView ivDeletePass;
    @BindView(R.id.btn_get_test)
    Button btnGetTest;
    @BindView(R.id.btn_done)
    Button btnDone;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_code)
    EditText etCode;
    private String phoneNum;
    private String password;
    private String vinCode;

    private Timer  timer;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what >= 0){

                btnGetTest.setText("(" + msg.what + ")" + "重新获取");
                btnGetTest.setBackgroundResource(R.drawable.shape_unclick);
                btnGetTest.setClickable(false);
            }else {

                timer.cancel();
                btnGetTest.setText("获取验证码");
                btnGetTest.setBackgroundResource(R.drawable.shape_get);
                btnGetTest.setClickable(true);
            }
        }
    };
    private boolean isPhone;
    private boolean isPassword;
    private RegisterResponse registerResponse;
    private String strMessage;
    private String strStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_pass);
        ButterKnife.bind(this);


        phoneNum = etPhone.getText().toString();
        password = etPassword.getText().toString();
        vinCode = etCode.getText().toString();

        isPhone = isPhoneNumber(phoneNum);
        isPassword = isPassWord(password);

        initData();
    }

    //    @OnClick(R.id.iv_return)
//    void setIvReturn(){
//        finish();
//    }
//
//    @OnClick(R.id.btn_done)
//    void setBtnDone(){
//
//
//
//
//    }
    private void initData() {


        ivReturn.setOnClickListener(this);
        ivDeletePass.setOnClickListener(this);
        btnDone.setOnClickListener(this);
        btnGetTest.setOnClickListener(this);
    }


    //点击事件的实现


    @Override
    public void onClick(View view) {


        switch (view.getId()){

            case R.id.iv_return:

                //返回
                finish();
                break;

            case R.id.iv_delete_pass:

                //删除所输入的密码
                etPassword.setText("");
                break;


            case R.id.btn_done:

                findPassword();
                break;

            case R.id.btn_get_test:

                getVinCode();

                break;

        }
    }


    //请求找回密码
    public void findPassword(){

        //请求网络将新的密码上传到服务器
        OkHttpUtils.postString()
                .url(NetURL.ForgetDone)
                .content(new Gson().toJson(new User(phoneNum,password,vinCode)))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                        Log.i("11",e.getMessage());
                    }

                    @Override
                    public void onResponse(String response) {

                        registerResponse = JsonParse.getFromJson(response,RegisterResponse.class);
                        strMessage = registerResponse.getMessage();
                        strStatus = registerResponse.getStatus();
                        int state = Integer.parseInt(strStatus);

                        if (state == 0){

                            //自定义toast提示密码修改成功
                            LayoutInflater inflater = getLayoutInflater();
                            View view = inflater.inflate(R.layout.layout_set_toast, null);
                            Toast toast = new Toast(FindPassActivity.this);
                            toast.setGravity(Gravity.CENTER, 0, 25);
                            toast.setDuration(Toast.LENGTH_SHORT);
                            toast.setView(view);
                            toast.show();
                        }else {

                            ToastUtils.showToast(FindPassActivity.this, strMessage);
                        }
                    }
                });
    }


    //请求获取验证码
    public void getVinCode(){

        if (phoneNum == null || phoneNum.equals("")){

            ToastUtils.showToast(this,"请输入电话号码");

        }else if (isPhone){


            OkHttpUtils.post()
                    .url(NetURL.FindMessage)
                    .addParams("mobile",phoneNum)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {

                        }

                        @Override
                        public void onResponse(String response) {

                            registerResponse = JsonParse.getFromJson(response,RegisterResponse.class);
                            strMessage = registerResponse.getMessage();
                            strStatus =  registerResponse.getStatus();
                            int state = Integer.parseInt(strStatus);

                            if (state == 1){

                                timeThread();
                            }else {

                                ToastUtils.showToast(FindPassActivity.this,strMessage);
                            }

                        }
                    });

        }else {

            ToastUtils.showToast(this,"请输入正确的电话号码");
        }



    }

    //手机号的正则表达判断是否为手机号
    private boolean isPhoneNumber(String phoneNum) {

        String pattern = "(13\\d|14[57]|15[^4,\\D]|17[678]|18\\d)\\d{8}|170[059]\\d{7}";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(phoneNum);

        return m.find();
    }


    //密码的正则
    private boolean isPassWord(String passWord) {

        String passRegex = "^[a-zA-Z0-9]{6,12}$";

        Pattern pattern = Pattern.compile(passRegex);
        Matcher matcher = pattern.matcher(passWord);

        return matcher.find();
    }


    private void timeThread() {
        TimerTask task = new TimerTask() {

            int i = 60;
            public void run() {

                mHandler.sendEmptyMessage(i);
                i--;

            }
        };

        timer = new Timer(true);
        timer.schedule(task,0, 1000); //延时1000ms后执行，1000ms执行一次

    }
}
